#include "headfiles.h"

using namespace std;

// 2d memory allocation with m rows and n columns
void ** twoDMalloc(size_t m, size_t n, size_t elem_size) {
    if (m == 0 ||
        n == 0 || 
        elem_size == 0) {
        cout << "Invalid input arguments!" << endl;
        return NULL;
    }

    size_t total_size = m * sizeof(void *) + m * n * elem_size;
    size_t i;
    char *orig_ptr = (char *)malloc(total_size);
    size_t buffer_offset = m * sizeof(void *);
    char *buffer_ptr = orig_ptr + buffer_offset;
    void **ptr_ptr = (void **)orig_ptr;
    for (i = 0; i < m; i++) {
        ptr_ptr[i] = buffer_ptr + i * elem_size * n;
    }

    return ptr_ptr;
}

void twoDFree(void **ptr) {
    if (ptr == NULL) {
        return;
    }

    free((void *)ptr);

    return;
}

